from sqlalchemy import *
from core.db import *
from core import *
import re

class qComment(object):
	pass
class qWordComment(object):
	pass
	
comment_table = Table('comment_table',metadata,
		Column('id',Integer,primary_key=True),
		Column('embedded',Integer),
		Column('fa',String))

word_comment_table = Table('word_comment_table',metadata,
		Column('id',Integer,primary_key=True),
		Column('comment_id',Integer,ForeignKey("comment_table.id")),
		Column('word_id',Integer,ForeignKey("word_table.id")),
		Column('last',Integer))



comment_mapper = mapper(qComment,comment_table)
comment_query = session.query(qComment)
word_comment_mapper = mapper(qWordComment,word_comment_table,properties={
	'comment':relation(qComment,backref=backref('words',cascade="delete,save-update,refresh-expire")),
	'word':relation(qpath.qWord,backref=backref('comments',cascade="delete,save-update,refresh-expire"))})
word_comment_mapper = session.query(qWordComment)


def isSupportQuery(query,domain=""):
	r = re.compile("^\s*comment{([^}]*)}\s*$").search(query)
	return (r != None)
	
def start_filter(sureQ,ayeQ,query):
	log.logger.debug('servers.comment.start_filter(%s,%s,%s)' % (sureQ,ayeQ,query))
	r = re.compile("^\s*comment{([^}]*)}\s*$").search(query)
	q = r.group(1)
	result = []
	ww = [com.words[0].word for com in comment_query.select(qComment.c.fa.like("%"+q+"%"))]
	for w in ww:
		if qpath.isWordInQPath(w,sureQ,ayeQ):
			result.append(w)
	log.logger.debug('	result:%d' % len(result))		
	return result		


def filter(query,domain):
	"""
	will filter queries with format
	"comment{REGULAR_EXPRESSION}" on domain and return results
	"""
	r = re.compile("^\s*comment{([^}]*)}\s*$").search(query)
	query = r.group(1)
	result = []
	d1 = []
	for d in domain:
		if isinstance(d,qpath.qAye) :
			d1 = dl + d.words
		if isinstance(d,qpath.qSure) :
			for a in d.ayat:
				d1 = d1 + a.words
		if isinstance(d,qpath.qWord) :
			d1.append(d)
	reg = re.compile(query)		
	for x in d1:
		for c in x.comments:
			regr = reg.search(x.comment.fa)
			if regr != None:
				result.append(x)
				break;	
	return result

log.logger.info("adding comment module to qpath server")

qpath.server_isSupports.append(isSupportQuery)
qpath.server_filter.append(filter)

qpath.server_isStartSupports.append(isSupportQuery)
qpath.server_start_filter.append(start_filter)


if __name__ == "__main__":
	pass
